package servlet;

import javax.jms.*;
import javax.naming.*;
import javax.annotation.Resource;
import java.util.*;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * @author jparra
 */
public class GestorQueue extends HttpServlet implements MessageListener {

    private static ServletContext sc;
    @Resource(mappedName = "jms/queueFactory")
    javax.jms.QueueConnectionFactory queueConnectionFactory;
    @Resource(mappedName = "jms/queue")
    javax.jms.Queue queue;
    Connection connectionListener = null;
    QueueSession sessionListener = null;
    QueueReceiver receptorListener = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sc = this.getServletContext();
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String operacion = request.getParameter("operacion"); // recibe parametro que indica el tipo de operacion

        if (operacion.equalsIgnoreCase("enviar")) {
            this.doEnviar(request, response);
            return;
        }

        if (operacion.equalsIgnoreCase("listar")) {
            this.doListar(request, response);
            return;
        }

        if (operacion.equalsIgnoreCase("recibir")) {
            this.doRecibir(request, response);
            return;
        }

        if (operacion.equalsIgnoreCase("activar")) {
            this.doActivar(request, response);
            return;
        }

    }

    public void doEnviar(HttpServletRequest request, HttpServletResponse response) {
        try {
            String text = request.getParameter("mensaje");
            Connection connection = queueConnectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            TextMessage message = session.createTextMessage(text);
            MessageProducer producer = session.createProducer(queue);
            producer.send(message);
            producer.close();
            session.close();
            connection.close();
            String texto = "Se ha enviado el mensaje correctamente";
            request.setAttribute("texto", texto);
            RequestDispatcher rd = sc.getRequestDispatcher("/index.jsp");
            rd.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void doListar(HttpServletRequest request, HttpServletResponse response) {
        try {
            
            String texto = "";
            Connection connection = queueConnectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueBrowser browser = session.createBrowser(queue);
            Enumeration queueEnum = browser.getEnumeration();
            while (queueEnum.hasMoreElements()) {
                Object obj = queueEnum.nextElement();
                if (obj instanceof TextMessage) {
                    texto += "Mensaje: " + ((TextMessage) obj).getText() + "<br>";
                }
            }
            browser.close();
            session.close();
            connection.close();
            request.setAttribute("texto", texto);
            RequestDispatcher rd = sc.getRequestDispatcher("/receptor.jsp");
            rd.forward(request, response);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doRecibir(HttpServletRequest request, HttpServletResponse response) {
        try {
            
            System.err.println("doRecibir");
            String texto = "No hay mensaje";
            Connection connection = queueConnectionFactory.createConnection();
            QueueSession session = (QueueSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueReceiver receptor = session.createReceiver(queue);
            System.err.println("doRecibir2");
            connection.start();
            System.err.println("doRecibir3");
            Object obj = receptor.receive();
            //request.setAttribute("listener", "true");
            if (obj instanceof TextMessage) {
                texto = "Mensaje recibido: " + ((TextMessage) obj).getText() + "<br>";
            }
            System.err.println("doRecibir4");
            receptor.close();
            session.close();
            connection.close();
            request.setAttribute("texto", texto);
            
            RequestDispatcher rd = sc.getRequestDispatcher("/receptor.jsp");
            System.err.println("doRecibir5");
            rd.forward(request, response);
            //request.setAttribute("listener", "true");
            //this.doActivar(request, response);
            //return;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doActivar(HttpServletRequest request, HttpServletResponse response) {
        try {
            Connection connection = queueConnectionFactory.createConnection();
            QueueSession session = (QueueSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueReceiver receptor = session.createReceiver(queue);
            receptor.setMessageListener(this);
            connection.start();
            String texto = "Listener activo, los mensajes se muestran por la salida del servidor.<br>Para parar el listener deberá parar el servidor.";
            request.setAttribute("texto", texto);
            request.setAttribute("listener", "true");
            RequestDispatcher rd = sc.getRequestDispatcher("/receptor.jsp");
            rd.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void onMessage(Message m) {
        try {
            if (m instanceof TextMessage) {
                TextMessage mens = (TextMessage) m;
                System.out.println("Mensaje recibido: " + mens.getText());
            } else {
                System.out.println("Formato de mensaje erroneo");
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
